package com.example.user.aspect;

import com.example.common.core.constants.Constants;
import com.example.common.core.enums.ResultCode;
import com.example.common.core.utils.ThreadLocalUtil;
import com.example.common.security.exception.ServiceException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class UserIdentityCheckAspect {
    @Before(value = "@within(com.example.user.aspect.CheckUserIdentity) || @annotation(com.example.user.aspect.CheckUserIdentity)")
    public void before(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        CheckUserIdentity checkUserRole = null;
        
        // 先检查方法上是否有注解
        checkUserRole = signature.getMethod().getAnnotation(CheckUserIdentity.class);
        
        // 如果方法上没有注解，则检查类上是否有注解
        if (checkUserRole == null) {
            checkUserRole = signature.getMethod().getDeclaringClass().getAnnotation(CheckUserIdentity.class);
        }
        
        // 如果都没有注解，则直接返回
        if (checkUserRole == null) {
            return;
        }
        
        Integer identity = ThreadLocalUtil.get(Constants.USER_IDENTITY, Integer.class);
        // 检查用户角色是否匹配
        if (identity != checkUserRole.identity().getValue()) {
            throw new ServiceException(ResultCode.NO_PERMISSION);
        }
    }
}
